package com.incar.chuxing.activity.driving;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.incar.chuxing.R;
import com.incar.chuxing.activity.PhotoViewActivity;
import com.incar.chuxing.activity.WebViewActivity;
import com.incar.chuxing.activity.personal.ContactServiceActivity;
import com.incar.chuxing.adapter.BottomDialogAdapter;
import com.incar.chuxing.adapter.GridViewAddImgesAdpter;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.ParseApiStore;
import com.incar.chuxing.api.RxApiStore;
import com.incar.chuxing.api.UrlContainer;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.AppConstants;
import com.incar.chuxing.bean.BleLogBean;
import com.incar.chuxing.bean.CheckPositionBean;
import com.incar.chuxing.bean.CommonResultBean;
import com.incar.chuxing.bean.ForbidArea;
import com.incar.chuxing.bean.ReturnCarBean;
import com.incar.chuxing.bean.ReturnCarCommentBean;
import com.incar.chuxing.bean.ReturnCarEvent;
import com.incar.chuxing.bean.ReturnGoldTipBean;
import com.incar.chuxing.bean.ReturnOilBean;
import com.incar.chuxing.bean.TravelDetailBean;
import com.incar.chuxing.bean.UploadImageBaidu;
import com.incar.chuxing.utils.AntiShake;
import com.incar.chuxing.utils.AppManager;
import com.incar.chuxing.utils.CheckRegexUtils;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.Dialogs.DialogOneButton;
import com.incar.chuxing.utils.Dialogs.DialogTwoButton;
import com.incar.chuxing.utils.IntentKey;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.NetUtils;
import com.incar.chuxing.utils.SPKey;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.ToastUtils;
import com.incar.chuxing.utils.ble.BleConstants;
import com.incar.chuxing.utils.ble.BluetoothHelper;
import com.incar.chuxing.utils.bos.UploadPicUtil;
import com.incar.chuxing.utils.wangyiqiyu.ConsultService;
import com.incar.chuxing.widget.NoScrollGridView;
import com.qiyukf.unicorn.api.Unicorn;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.incar.chuxing.utils.ble.BluetoothHelper.REQUEST_OPEN_BLE_ONCE;

public class ReturnCarActivity extends BaseActivity {

    @BindView(R.id.return_message_tv)
    TextView returnMessageTv;
    @BindView(R.id.return_message)
    LinearLayout returnMessage;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_return)
    TextView tvReturn;
    @BindView(R.id.linear_warn)
    LinearLayout linear_warn;
    @BindView(R.id.tv_warnmoney)
    TextView tv_warnmoney;
    @BindView(R.id.cancel_reason)
    NoScrollGridView mGridView;
    @BindView(R.id.scroll_content)
    NestedScrollView scrollContent;
    @BindView(R.id.cancel_reason_frame)
    LinearLayout cancelReasonFrame;
    @BindView(R.id.choose_type)
    RelativeLayout choose_type;
    @BindView(R.id.choose_type_tv)
    TextView choose_type_tv;
    @BindView(R.id.return_car_pics_gridView)
    NoScrollGridView returnCarPicsGridView;
    @BindView(R.id.return_car_in_park_name)
    EditText returnCarInParkName;
    @BindView(R.id.return_car_in_park_num)
    EditText returnCarInParkNum;
    @BindView(R.id.return_car_in_park_ground)
    TextView return_car_in_park_ground;
    @BindView(R.id.return_car_in)
    LinearLayout returnCarIn;

    @BindView(R.id.layout_return_gold_tip)
    RelativeLayout layoutReturnGoldTip;
    @BindView(R.id.return_gold_tip)
    TextView returnGoldTip;
    @BindView(R.id.radio_button_free)
    RadioButton radioButtonFree;
    @BindView(R.id.radion_button_charge)
    RadioButton radioButtonCharge;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;

    private ArrayList<String> datas;
    private GridViewAddImgesAdpter gridViewAddImgesAdpter;

    private Context mContext = this;
    private GridViewAdapter gridViewAdapter;

    private String orderId, carId, orderNum;
    private TravelDetailBean.AttachmentBean result;
    public BleConstants.ControlType controlType;
    private int connectTimes;
    private boolean canBack = true;
    private String key, imgs;
    private String onGround = "";
    private String remarkMsg;
    private String remarkMsgUp;
    private BottomDialogAdapter rcAdapter;
    private int rentType;
    private int bookType;

    @Override
    public int getLayoutId() {
        return R.layout.activity_car_return;
    }

    @Override
    public void initData() {
        super.initData();
        orderId = getIntent().getStringExtra("orderId");
        carId = getIntent().getStringExtra("carId");
        orderNum = getIntent().getStringExtra("orderNum");
        rentType = getIntent().getIntExtra("rentType", 0);
        bookType = getIntent().getIntExtra("bookType", 0);
        checkPosition(orderId, carId);
    }


    @Override
    public void initView() {

        returnCarInParkNum.setTransformationMethod(new ReplacementTransformationMethod() {
            @Override
            protected char[] getOriginal() {
                char[] originalCharArr = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
                return originalCharArr;
            }

            @Override
            protected char[] getReplacement() {
                char[] replacementCharArr = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
                return replacementCharArr;
            }
        });

        returnCarInParkNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(returnCarInParkNum.getText().toString()))
                    SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PARKNUM, returnCarInParkNum.getText().toString() + "");
            }
        });


        if (!TextUtils.isEmpty(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_MESSAGE))) {
            returnMessage.setVisibility(View.VISIBLE);
            returnMessageTv.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_MESSAGE));
        }

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (canBack) {
                    AppManager.getAppManager().finishActivity();
                }
            }
        });

        //cache
        returnCarInParkName.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PARKNAME));
        if (null != SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PARKNUM))
            returnCarInParkNum.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PARKNUM));
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_SPINNER_NAME) != null) {
            choose_type_tv.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_SPINNER_NAME));
            return_car_in_park_ground.setText(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_SPINNER_NAME));
        }
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_POSITION) != null) {
            if ("0".equals(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_POSITION))) {
                returnCarIn.setVisibility(View.VISIBLE);
                returnCarPicsGridView.setVisibility(View.GONE);
                onGround = "0";
            } else if ("1".equals(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_POSITION))) {
                returnCarIn.setVisibility(View.GONE);
                returnCarPicsGridView.setVisibility(View.VISIBLE);
                onGround = "1";
            }
        }
        //indoor
        returnCarInParkName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollContent.scrollTo(returnCarInParkName.getScrollX(), returnCarInParkName.getScrollY());
                Intent intent = new Intent(mContext, SearchParkActivity.class);
                intent.putExtra("content", returnCarInParkName.getText().toString());
                startActivity(intent);
            }
        });
        //outDoor
        datas = new ArrayList<>();
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC) != null) {
            File fileDir = new File(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC));
            File[] files = fileDir.listFiles();
            if (null != files) {
                Arrays.sort(files);
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId)) {
                        Logger.d("returnCarrename3", files[i].getAbsolutePath());
                        datas.add(files[i].getAbsolutePath());
                    }
                }
            }
        } else {
            datas = null;
        }
        gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, mContext);
        returnCarPicsGridView.setAdapter(gridViewAddImgesAdpter);
        returnCarPicsGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (datas == null || datas.size() == position) {
                    Intent intent = new Intent(mContext, ReturnCarCameraActivity.class);
                    intent.putExtra("orderId", orderId);
                    startActivity(intent);
                } else {
                    Logger.d("returnCarrename4", "click--" + position);
                    Intent intent = new Intent(mContext, PhotoViewActivity.class);
                    intent.putStringArrayListExtra("pictures", datas);
                    intent.putExtra("pictureType", 1);
                    intent.putExtra("toIndex", position);
                    int location[] = new int[2];
                    view.getLocationOnScreen(location);
                    intent.putExtra("left", location[0]);
                    intent.putExtra("top", location[1]);
                    intent.putExtra("height", view.getHeight());
                    intent.putExtra("width", view.getWidth());
                    mContext.startActivity(intent);
                    ((ReturnCarActivity) mContext).overridePendingTransition(0, 0);
                }
            }
        });
        //停车场类型
        Logger.i("selcegtesag", SPUtils.getInstance(mContext).getIntValue(SPKey.PARK_TYPE_SELECT) + "");
        if (SPUtils.getInstance(mContext).getIntValueWithDef(SPKey.PARK_TYPE_SELECT, 1) == 0) {
            radioGroup.setVisibility(View.GONE);
        } else {
            radioGroup.setVisibility(View.VISIBLE);
        }
    }


    @OnClick({R.id.tv_return, R.id.choose_type})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) return;    //判断是否多次点击
        switch (view.getId()) {
            case R.id.tv_return:
                if (!NetUtils.isNetworkAvailable(mContext)) {
                    ToastUtils.makeText(mContext, "无网络连接，请检查网络连接", ToastUtils.LENGTH_SHORT).show();
                    return;
                }

                ParseApiStore.getInstance().commitClickReturnCarLog(carId, orderId);
                if (getPermissionAndGps()) {
                    checkUserInput(orderId, carId);
                }

                break;
            case R.id.choose_type:
                showBottomSheetDialog();
                break;
        }

    }

    private void dayRentOilTip() {
        showLoadingDialog();
        RxApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getOilRemain(MyApplication.getInstance().getRequestFieldMap(), carId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ReturnOilBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ReturnOilBean returnOilBean) {
                        dismissLoadingDialog();
                        if (returnOilBean.getStatus() == 200) {
                            DialogOneButton oilTipDialog = new DialogOneButton(mContext);
                            oilTipDialog.setMessage("当前油量" + returnOilBean.getAttachment().getCarOil() + "L");
                            oilTipDialog.setYesOnclickListener("知道了", () -> {
                                oilTipDialog.dismiss();
                                returnCarComment(imgs, orderId, carId);
                            });
                            oilTipDialog.show();
                        } else {
                            ToastUtils.makeText(mContext, returnOilBean.getMessage(), ToastUtils.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private boolean getPermissionAndGps() {
        boolean permissionOk;
        boolean gpsOk;
        permissionOk = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断是否开启了GPS，如果没有则开启
        gpsOk = (locationManager == null) || (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));

        if (!permissionOk) {
            Logger.i("dingwei", "定位权限关闭");
            DialogTwoButton dialogButton = new DialogTwoButton(mContext);
            dialogButton.setTitle("定位权限已关闭");
            dialogButton.setMessage("您需要开启定位权限，才可以查看车辆情况，请到设置的权限管理中开启【大道用的】定位权限。");
            dialogButton.setCancelable(false);
            dialogButton.setCanceledOnTouchOutside(false);
            dialogButton.setYesOnclickListener("设置", () -> {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
                dialogButton.dismiss();
            });
            dialogButton.setNoOnclickListener("取消", () -> {
                dialogButton.dismiss();
            });
            dialogButton.show();
            return false;
        }

        if (!gpsOk) {
            Logger.i("dingwei", "定位Gps关闭");
            DialogTwoButton inCarDialog = new DialogTwoButton(this);
            inCarDialog.setTitle("GPS定位已关闭");
            inCarDialog.setMessage(getString(R.string.LocationServiceRemind));
            inCarDialog.setYesOnclickListener("设置", () -> {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, Constants.REQUEST_LOCATION_SERVICE);
                inCarDialog.dismiss();
            });
            inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
            inCarDialog.setCanceledOnTouchOutside(true);
            inCarDialog.setCancelable(true);
            inCarDialog.show();
            return false;
        }
        return true;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //indoor
        if (intent.getStringExtra("searchParkName") != null) {
            returnCarInParkName.setText(intent.getStringExtra("searchParkName"));
            SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PARKNAME, returnCarInParkName.getText().toString() + "");
        }
        //outdoor
        datas = new ArrayList<>();
        if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC) != null) {
            File fileDir = new File(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC));
            File[] files = fileDir.listFiles();
            if (files != null) {
                Arrays.sort(files);
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId)) {
                        Logger.d("returnCarrename3OnNewIntent", files[i].getAbsolutePath());
                        datas.add(files[i].getAbsolutePath());
                    }
                }
            }

        } else {
            datas = null;
        }
        gridViewAddImgesAdpter.notifyDataSetChanged(datas);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
        } else if (requestCode == REQUEST_OPEN_BLE_ONCE && resultCode == Activity.RESULT_OK) {
            dismissLoadingDialog();
        }
    }

    /*
     * Java文件操作 获取不带扩展名的文件名
     */
    public String getFileNameNoEx(File nameFile) {
        String filename = nameFile.getName();
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                int index = filename.indexOf("-");
                return filename.substring(index + 1, dot);
            }
        }
        return filename;
    }

    private void checkUserInput(final String orderId, String carId) {
        confirmR = null;
        showLoadingDialog();
        if ("1".equals(onGround)) {
            remarkMsg = remarkMsgUp;
            if (gridViewAddImgesAdpter.getCount() - 1 <= 0) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, "请先拍摄还车位置", ToastUtils.LENGTH_SHORT).show();
                return;
            }
        } else if ("0".equals(onGround)) {
            if (null != returnCarInParkName.getText() && null != returnCarInParkNum.getText()) {
                remarkMsg = returnCarInParkName.getText().toString() + return_car_in_park_ground.getText().toString() + returnCarInParkNum.getText().toString();
            }

            if (!CheckRegexUtils.checkParkName(returnCarInParkName.getText().toString())) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, "请填写停车场名称", ToastUtils.LENGTH_SHORT).show();
                return;
            } else if (TextUtils.isEmpty(returnCarInParkNum.getText().toString())) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, "请填写停车区号及车位编号", ToastUtils.LENGTH_SHORT).show();
                return;
            }
        } else {
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "请先选择还车位置", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        if (radioGroup.getVisibility() == View.VISIBLE && !radioButtonFree.isChecked() && !radioButtonCharge.isChecked()) {
            dismissLoadingDialog();
            String parkTips = SPUtils.getInstance(mContext).getStringValue(SPKey.PARK_TYPE_TIP, "请选择停车场类型");
            ToastUtils.makeText(mContext, parkTips, ToastUtils.LENGTH_SHORT).show();
            return;
        }


        if ("1".equals(onGround) && SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC) != null) {//地上
            List<String> success = new ArrayList<>();
            if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME) != null) {
                success = Arrays.asList(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME).split(","));
            }
            File fileDir = new File(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC));
            File[] files = fileDir.listFiles();
            List<File> unUpdatePics = new ArrayList<>();
            if (files != null) {
                Arrays.sort(files);
                imgs = "";
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId) && !success.contains(files[i].getName())) {
                        unUpdatePics.add(files[i]);
                    }
                }
            }

            if (unUpdatePics.size() != 0) {
                Observable
                        .fromIterable(unUpdatePics)
                        .flatMap(new Function<File, ObservableSource<UploadImageBaidu>>() {
                            @Override
                            public ObservableSource<UploadImageBaidu> apply(File file) throws Exception {
                                return Observable.create(new ObservableOnSubscribe<UploadImageBaidu>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<UploadImageBaidu> emitter) throws Exception {
                                        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).uploadImageBaidu(MyApplication.getInstance().getRequestFieldMap(), "stsToken", "upload").enqueue(new Callback<UploadImageBaidu>() {
                                            @Override
                                            public void onResponse(Call<UploadImageBaidu> call, Response<UploadImageBaidu> response) {
                                                Logger.d("预备上传" + response.body().getAttachment().getBucketName());
                                                response.body().setFile(file);
                                                emitter.onNext(response.body());
                                                emitter.onComplete();
                                            }

                                            @Override
                                            public void onFailure(Call<UploadImageBaidu> call, Throwable t) {
                                                emitter.onComplete();
                                            }
                                        });
                                    }
                                });
                            }
                        })
                        .flatMap(new Function<UploadImageBaidu, ObservableSource<File>>() {
                            @Override
                            public ObservableSource<File> apply(UploadImageBaidu uploadImageBaidu) throws Exception {

                                return Observable.create(new ObservableOnSubscribe<File>() {
                                    @Override
                                    public void subscribe(ObservableEmitter<File> emitter) throws Exception {
                                        Logger.d("上传 开始" + uploadImageBaidu.getFile() + "   " + uploadImageBaidu.getAttachment().getBucketName());
                                        key = getFileNameNoEx(uploadImageBaidu.getFile());
                                        UploadPicUtil.getInstance().uploadPicToBos(
                                                uploadImageBaidu.getFile(),
                                                uploadImageBaidu.getAttachment().getAk(),
                                                uploadImageBaidu.getAttachment().getSk(),
                                                uploadImageBaidu.getAttachment().getBucketName(),
                                                uploadImageBaidu.getAttachment().getStsToken(),
                                                uploadImageBaidu.getAttachment().getBucketName(),
                                                key,
                                                new UploadPicUtil.OnFinishListener() {
                                                    @Override
                                                    public void onSuccess() {
                                                        SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_PIC_NAME, SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_NAME) + "," + uploadImageBaidu.getFile().getName());
                                                        emitter.onNext(uploadImageBaidu.getFile());
                                                        emitter.onComplete();
                                                        Logger.d("returnCar", "上传成功" + uploadImageBaidu.getFile().getName());
                                                    }

                                                    @Override
                                                    public void onFailure(String failReason) {
                                                        emitter.onComplete();
                                                        Logger.d("returnCar", "上传失败  " + failReason + "    " + uploadImageBaidu.getFile().getName());
                                                    }
                                                });
                                    }
                                });
                            }
                        }).subscribe(new Observer<File>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(File file) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        for (int i = 0; i < files.length; i++) {
                            if (files[i].getName().endsWith("jpg") && files[i].getName().startsWith(orderId)) {
                                String name = getFileNameNoEx(files[i]);
                                imgs = imgs + name + ",";
                            }
                        }
                        if (rentType == 2) {
                            //日租车提示还车油量
                            dayRentOilTip();
                        } else {
                            returnCarComment(imgs, orderId, carId);
                        }
                    }
                });
            } else {
                for (File file : files) {
                    if (file.getName().endsWith("jpg") && file.getName().startsWith(orderId)) {
                        String name = getFileNameNoEx(file);
                        imgs = imgs + name + ",";
                    }
                }
                if (rentType == 2) {
                    //日租车提示还车油量
                    dayRentOilTip();
                } else {
                    returnCarComment(imgs, orderId, carId);
                }

            }

        } else {
            if (rentType == 2) {
                //日租车提示还车油量
                dayRentOilTip();
            } else {
                returnCarComment(imgs, orderId, carId);
            }
        }

    }


    private void returnCarComment(String imgs, String orderId, String carId) {
        showLoadingDialog();
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson = new JSONObject(new Gson().toJson(MyApplication.getInstance().getRequestFieldMap()));
            bodyJson.put("car_id", carId);
            JSONObject commentJson = new JSONObject();
            commentJson.put("onGround", onGround);
            if (imgs != null) {
                commentJson.put("imgs", imgs);
            }
            commentJson.put("remarkMsg", remarkMsg == null ? "" : remarkMsg.toUpperCase());
            commentJson.put("orderId", orderId);
            if (radioGroup.getVisibility() == View.VISIBLE) {
                commentJson.put("free_parking", radioButtonFree.isChecked() ? "2" : "1");
            }
            bodyJson.put("comment", commentJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Logger.d("returnCar", bodyJson.toString());
        if (!TextUtils.isEmpty(imgs)) {
            key = imgs.substring(0, imgs.indexOf(","));
        }
        Logger.d("returnCar_key", key);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).returnCarComment(body).enqueue(new Callback<ReturnCarCommentBean>() {
            @Override
            public void onResponse(Call<ReturnCarCommentBean> call, Response<ReturnCarCommentBean> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getMsg_code() == 200) {
                    checkForbidArea(carId, orderId);
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ReturnCarCommentBean> call, Throwable t) {
                Logger.i("return car", t.getMessage());
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();

            }
        });
    }

    private void offElectricity(String carId, String orderId) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).offElectricity(MyApplication.getInstance().getRequestFieldMap(), orderId, carId).enqueue(new Callback<CommonResultBean>() {
            @Override
            public void onResponse(Call<CommonResultBean> call, Response<CommonResultBean> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getStatus() == 200) {
                    returnCar(orderId, carId, null, null);
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResultBean> call, Throwable t) {
                Logger.i("return car", t.getMessage());
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();

            }
        });

    }

    //查询是否在还车区域
    private void checkForbidArea(String carId, String orderId) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).checkoutForbidArea(carId, MyApplication.getInstance().getAreaCode(), ((MyApplication) getApplication()).getUid(), orderNum).enqueue(new Callback<ForbidArea>() {
            @Override
            public void onResponse(Call<ForbidArea> call, Response<ForbidArea> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().isValidResult()) {
                            offElectricity(carId, orderId);
                        } else {
                            dismissLoadingDialog();
                            if (response.body().getAttachment().getBtnType() == 0) {
                                final DialogTwoButton inCarDialog = new DialogTwoButton(ReturnCarActivity.this);
                                inCarDialog.setTitle(response.body().getAttachment().getFailureReason());
                                inCarDialog.setMessage(response.body().getAttachment().getSuggestion());
                                inCarDialog.setYesOnclickListener("取消", new DialogTwoButton.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        dismissLoadingDialog();
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setNoOnclickListener("继续还车", new DialogTwoButton.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        offElectricity(carId, orderId);
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setCancelable(false);
                                inCarDialog.show();
                            } else if (response.body().getAttachment().getBtnType() == 2) {
                                final DialogTwoButton inCarDialog = new DialogTwoButton(ReturnCarActivity.this);
                                inCarDialog.setTitle(response.body().getAttachment().getFailureReason());
                                inCarDialog.setMessage(response.body().getAttachment().getSuggestion());
                                inCarDialog.setYesOnclickListener("好的", new DialogTwoButton.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        dismissLoadingDialog();
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setNoOnclickListener("查看说明", new DialogTwoButton.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        Intent intent = new Intent();
                                        intent.setClass(mContext, WebViewActivity.class);
                                        intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, response.body().getAttachment().getNoticeUrl());
                                        startActivity(intent);
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setCancelable(false);
                                inCarDialog.show();
                            } else {
                                ToastUtils.makeText(mContext, response.body().getAttachment().getFailureReason() + response.body().getAttachment().getSuggestion(), ToastUtils.LENGTH_SHORT).show();
                            }
                        }
                    } else {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    dismissLoadingDialog();
                    ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ForbidArea> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    private String confirmR;

    //confirmR=402强制还车
    private void returnCar(String orderId, String carId, String isBluetoothConnect, String logType) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).returnCar(
                ((MyApplication) getApplication()).getRequestFieldMap(), orderId, carId, "", remarkMsg != null ? remarkMsg.toUpperCase() : "",
                isBluetoothConnect, key, gridViewAdapter != null && !gridViewAdapter.getSelectId().equals("-1") ? gridViewAdapter.getSelectId() : null,
                logType, confirmR)
                .enqueue(new Callback<ReturnCarBean>() {
                    @Override
                    public void onResponse(Call<ReturnCarBean> call, Response<ReturnCarBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Logger.i("return car", "returnType" + logType + "   " + new Gson().toJson(response.body()));
                            if (response.body().getStatus() == 200) {
                                canBack = false;
                                tvReturn.setClickable(false);
                                dismissLoadingDialog();
                                EventBus.getDefault().post(new ReturnCarEvent(true));//结束掉行驶中页
                                if (BluetoothHelper.getInstance().isConnect()) {
                                    BluetoothHelper.getInstance().disConnectDevice();
                                }
                                BluetoothHelper.getInstance().removeBleInfo(mContext);

                                //清除照片
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PIC_NAME);
                                if (SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC) != null) {
                                    File fileDir = new File(SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_PIC_DIC));
                                    File[] files = fileDir.listFiles();

                                    if (files != null) {
                                        Arrays.sort(files);
                                        for (int i = 0; i < files.length; i++) {
                                            if (files[i].getName().endsWith("jpg")) {
                                                files[i].delete();
                                            }
                                        }
                                    }
                                }
                                //清除cache
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_SPINNER_NAME);
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PARKNAME);
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_PARKNUM);
                                SPUtils.getInstance(mContext).removeValue(SPKey.RETURN_CAR_POSITION);

                                if (remarkMsg != null) { //如果选择了取消原因，Toast 1s后再跳转
                                    if (gridViewAdapter != null && !gridViewAdapter.getSelectId().equals("-1")) {
                                        ToastUtils.makeText(mContext, "感谢您的反馈", 0, ToastUtils.LENGTH_SHORT).show();
                                        new Handler().postDelayed(() -> {
                                            Intent intent = new Intent(mContext, WebViewActivity.class);
                                            intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "订单支付");
                                            CookieManager cookieManager = CookieManager.getInstance();
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "orderId=" + orderId);
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "oid=" + orderId);
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "rentType=" + rentType);
                                            cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "bookType=" + bookType);
                                            intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment) + "?oid=" + orderId + "&rentType=" + rentType + "&bookType=" + bookType);
                                            startActivity(intent);
                                            AppManager.getAppManager().finishActivity();

                                        }, 1500);
                                    } else {

                                        Intent intent = new Intent(mContext, WebViewActivity.class);
                                        intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "订单支付");
                                        CookieManager cookieManager = CookieManager.getInstance();
                                        cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "orderId=" + orderId);
                                        cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "oid=" + orderId);
                                        cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "rentType=" + rentType);
                                        cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "bookType=" + bookType);
                                        intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment) + "?oid=" + orderId + "&rentType=" + rentType + "&bookType=" + bookType);

                                        startActivity(intent);
                                        AppManager.getAppManager().finishActivity();

                                    }
                                } else {
                                    Intent intent = new Intent(mContext, WebViewActivity.class);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_TITLE, "订单支付");
                                    CookieManager cookieManager = CookieManager.getInstance();
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "orderId=" + orderId);
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "oid=" + orderId);
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "rentType=" + rentType);
                                    cookieManager.setCookie(UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment), "bookType=" + bookType);
                                    intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, UrlContainer.Request.h5UrlMap.get(UrlContainer.Request.html_payment) + "?oid=" + orderId + "&rentType=" + rentType + "&bookType=" + bookType);
                                    startActivity(intent);
                                    AppManager.getAppManager().finishActivity();
                                }


                            } else if (response.body().getStatus() == 10) {
                                if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                                    dismissLoadingDialog();
                                    dropOffCarBle();
                                } else {
                                    BluetoothHelper.getInstance().getBleInfo(carId, mContext, new BluetoothHelper.OnGetBleResponse() {
                                        @Override
                                        public void getBleResponse() {
                                            dismissLoadingDialog();
                                            if (BluetoothHelper.getInstance().isCarSupportBle(mContext)) {
                                                dropOffCarBle();
                                            } else {
                                                contactService();
                                            }
                                        }
                                    });
                                }
                            } else if (response.body().getStatus() == 402) {
                                final DialogTwoButton inCarDialog = new DialogTwoButton(ReturnCarActivity.this);
                                inCarDialog.setMessage(response.body().getMessage());
                                inCarDialog.setYesOnclickListener("取消", new DialogTwoButton.onYesOnclickListener() {
                                    @Override
                                    public void onYesClick() {
                                        dismissLoadingDialog();
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setNoOnclickListener("继续还车", new DialogTwoButton.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        confirmR = "402";
                                        returnCar(orderId, carId, BluetoothHelper.getInstance().isConnect() ? "1" : "0", null);
                                        inCarDialog.dismiss();
                                    }
                                });
                                inCarDialog.setCancelable(false);
                                inCarDialog.show();
                            } else {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_LONG).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ReturnCarBean> call, Throwable t) {
                        Logger.i("return car", t.getMessage());
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.opterateBadNetwork), ToastUtils.LENGTH_SHORT).show();
                    }
                });
    }

    private void dropOffCarBle() {
        controlType = BleConstants.ControlType.CLOSE_DOOR_POWEROFF;
        if (BluetoothHelper.getInstance().isBluetoothOpened()) {
            final DialogOneButton dialogOneButton = new DialogOneButton(mContext);
            dialogOneButton.setTitle("蓝牙已开启");
            dialogOneButton.setMessage("靠近车辆,蓝牙还车更顺畅");
            dialogOneButton.setCancelable(false);
            dialogOneButton.setCanceledOnTouchOutside(false);
            dialogOneButton.setYesOnclickListener("好的", new DialogOneButton.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    showLoadingDialog();
                    dialogOneButton.dismiss();
                    //蓝牙开，未连接
                    if (BluetoothHelper.getInstance().isBluetoothOpened() && !BluetoothHelper.getInstance().isConnect()) {
                        tvReturn.setClickable(false);
                        canBack = false;
                        String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                        BluetoothHelper.getInstance().searchDevice(3, bothSearchResponse, serialNumber);
                        //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "connect", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
                    }
                    //蓝牙开，已连接
                    else if (BluetoothHelper.getInstance().isBluetoothOpened() && BluetoothHelper.getInstance().isConnect()) {
                        String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                        BluetoothHelper.getInstance().operateCar(controlType, onOperateCarListener, serialNumber);
                        //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "closePowerDown", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
                    }
                }
            });
            dialogOneButton.show();
        } else {
            final DialogTwoButton inCarDialog = new DialogTwoButton(ReturnCarActivity.this);
            inCarDialog.setTitle("蓝牙未开启");
            inCarDialog.setMessage("靠近车辆，开启蓝牙还车更顺畅");
            inCarDialog.setYesOnclickListener("去开启", () -> {
                BluetoothHelper.getInstance().openBluetooth(ReturnCarActivity.this, REQUEST_OPEN_BLE_ONCE);
                inCarDialog.dismiss();
            });
            inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
            inCarDialog.setCancelable(false);
            inCarDialog.show();
        }
    }

    private void contactService() {
        final DialogTwoButton inCarDialog = new DialogTwoButton(ReturnCarActivity.this);
        inCarDialog.setTitle("蓝牙连接异常");
        inCarDialog.setMessage("是否联系客服处理?");
        inCarDialog.setYesOnclickListener("联系客服", () -> {
            inCarDialog.dismiss();
            if (Unicorn.isServiceAvailable()) {
                ConsultService consultService = new ConsultService(mContext);
                consultService.consultService(mContext, "", "", "", null);
            } else {
                Intent intent = new Intent();
                intent.setClass(mContext, ContactServiceActivity.class);
                startActivity(intent);
            }
        });
        inCarDialog.setNoOnclickListener("取消", () -> inCarDialog.dismiss());
        inCarDialog.setCancelable(false);
        inCarDialog.show();
    }

    BluetoothHelper.BothSearchResponse bothSearchResponse = new BluetoothHelper.BothSearchResponse() {

        @Override
        public void onSearchSuccess(String mac, String bleName, String serialNumber) {
            BluetoothHelper.getInstance().connectDevice(connectResponse, 3 - connectTimes);
        }

        @Override
        public void onSearchTimeoutEveryTime(String serialNumber) {
            Logger.i("bleinfo", "单次扫描超时");
            commitBleLog(orderId, carId, "101");
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "蓝牙连接失败\n请靠近车门，即将尝试重新连接", ToastUtils.LENGTH_LONG).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    showLoadingDialog();
                }
            }, 2600);
        }

        @Override
        public void onSearchTimeout(String serialNumber) {
            commitBleLog(orderId, carId, "101");
            dismissLoadingDialog();
            Logger.i("bleinfo", "扫描超时");
            //ParseApiStore.getInstance().commitBleResLog(serialNumber, "connect", "fail", "扫描超时,还车", null, BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            connectTimes++;
            contactService();
            tvReturn.setClickable(true);
            canBack = true;
        }
    };

    /**
     * 蓝牙连接的结果
     */
    BluetoothHelper.BothConnectResponse connectResponse = new BluetoothHelper.BothConnectResponse() {
        @Override
        public void onConnectSuccess(String serialNumber) {
            tvReturn.setClickable(true);
            canBack = true;
            commitBleLog(orderId, carId, "100");
            Logger.i("bleinfo", "连接上了");
            //ParseApiStore.getInstance().commitBleResLog(serialNumber, "connect", "success", null, null, BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            // 连接上立即发送数据会失败
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //再次刷新请求信息
                    String serialNumber = BluetoothHelper.getInstance().carBleName + "+" + new Date().getTime() / 1000;
                    BluetoothHelper.getInstance().operateCar(controlType, onOperateCarListener, serialNumber);
                    //ParseApiStore.getInstance().commitBleReqLog(serialNumber, "closePowerDown", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
                }
            }, 1000);
        }

        @Override
        public void onConnectTimeoutEveryTime(String serialNumber) {
            Logger.i("bleinfo", "单次连接失败");
            commitBleLog(orderId, carId, "101");
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "蓝牙连接失败\n请靠近车门，即将尝试重新连接", ToastUtils.LENGTH_LONG).show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    showLoadingDialog();
                }
            }, 2600);
        }

        @Override
        public void onConnectFailed(String error, String response, String serialNumber) {
            commitBleLog(orderId, carId, "101");
            dismissLoadingDialog();
            Logger.i("bleinfo", "连接失败");
            //ParseApiStore.getInstance().commitBleResLog(serialNumber, "connect", "fail", "连接失败,还车", response + "", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            contactService();
            tvReturn.setClickable(true);
            canBack = true;
        }

    };
    BluetoothHelper.OnOperateCarListener onOperateCarListener = new BluetoothHelper.OnOperateCarListener() {
        @Override
        public void onOperateSuccess(int[] status, String response, String serialNumber) {
            dismissLoadingDialog();
            commitBleLog(orderId, carId, "102");
            //BluetoothHelper.getInstance().removeBleInfo(mContext);
            if (controlType == BleConstants.ControlType.CLOSE_DOOR_POWEROFF) {
                //ToastUtils.makeText(mContext, "关门成功", ToastUtils.LENGTH_SHORT).show();
                //ParseApiStore.getInstance().commitBleResLog(serialNumber, "closePowerDown", "success", null, response + "", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            } else {
                ToastUtils.makeText(mContext, "操作成功", ToastUtils.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onOperateFailure(String error, String response, String serialNumber) {
            dismissLoadingDialog();
            if (controlType == BleConstants.ControlType.CLOSE_DOOR_POWEROFF) {
                commitBleLog(orderId, carId, "103");
                ToastUtils.makeText(mContext, "关门失败，请重新尝试", ToastUtils.LENGTH_SHORT).show();
                //ParseApiStore.getInstance().commitBleResLog(serialNumber, "closePowerDown", "fail", error + "", response + "", BluetoothHelper.getInstance().carType.getCarName() + "", SPUtils.getInstance(mContext).getStringValue(SPKey.USER_ID) + "", orderId, BluetoothHelper.getInstance().carBleName);
            } else {
                ToastUtils.makeText(mContext, "操作失败", ToastUtils.LENGTH_SHORT).show();
            }
        }
    };

    //发送蓝牙交互日志，logType100连接成功，101l扫描超时或者连接失败，102为还车成功
    private void commitBleLog(final String orderId, final String carId, final String logType) {
        String time = new Date().getTime() / 1000 + "";
        ApiStore.getInstance().getLogApiService(UrlContainer.Request.BASE_GATE_URL).commitBleLog(((MyApplication) getApplication()).getRequestFieldMap(), orderId, carId, logType, time).enqueue(new Callback<BleLogBean>() {
            @Override
            public void onResponse(Call<BleLogBean> call, Response<BleLogBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (logType.equals("102")) {
                            returnCar(orderId, carId, BluetoothHelper.getInstance().isConnect() ? "1" : "0", "102");
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<BleLogBean> call, Throwable t) {

            }
        });
    }

    private void checkPosition(final String orderId, String carId) {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getCheckPosition(((MyApplication) getApplication()).getRequestFieldMap(), orderId, carId).enqueue(new Callback<CheckPositionBean>() {
            @Override
            public void onResponse(Call<CheckPositionBean> call, Response<CheckPositionBean> response) {
                dismissLoadingDialog();
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        if (response.body().getAttachment().getList() != null && response.body().getAttachment().getList().size() != 0) {
                            cancelReasonFrame.setVisibility(View.VISIBLE);
                            gridViewAdapter = new GridViewAdapter();
                            mGridView.setAdapter(gridViewAdapter);
                            gridViewAdapter.replaceAll(response.body().getAttachment().getList());
                        } else {
                            cancelReasonFrame.setVisibility(View.GONE);
                            getGoldTip();
                        }

                        CheckPositionBean checkPositionBean = response.body();
                        if (!TextUtils.isEmpty(response.body().getAttachment().getUserRemark())) {
                            remarkMsgUp = response.body().getAttachment().getUserRemark();
                        } else {
                            remarkMsgUp = "点击图片查看车辆位置";
                        }

                        //0外 1内
                        if (checkPositionBean.getAttachment().getIsInFence() == 0 && checkPositionBean.getAttachment().getReturnMoney() != 0) {
                            linear_warn.setVisibility(View.VISIBLE);
                            DecimalFormat df = new DecimalFormat("0.00");
                            tv_warnmoney.setText("¥" + df.format(checkPositionBean.getAttachment().getReturnMoney() / 100) + "");
                        } else {
                            linear_warn.setVisibility(View.GONE);
                        }
                    } else {
                        ToastUtils.makeText(mContext, response.body().getMessage() + "!", ToastUtils.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<CheckPositionBean> call, Throwable t) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /*   private void getOrderDetail() {
           showLoadingDialog();
           ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getTravelDetail(((MyApplication) getApplication()).getRequestFieldMap(), orderId)
                   .enqueue(new Callback<TravelDetailBean>() {
                       @Override
                       public void onResponse(Call<TravelDetailBean> call, Response<TravelDetailBean> response) {
                           if (response.isSuccessful() && response.body() != null) {
                               if (response.body().getStatus() == 200) {
                                   result = response.body().getAttachment();
                                   carId = result.getCarModel().getId();
                                   checkPosition(orderId, carId);

                               } else {
                                   dismissLoadingDialog();
                                   ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                               }
                           } else {
                               dismissLoadingDialog();
                               ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), ToastUtils.LENGTH_SHORT).show();
                           }
                       }

                       @Override
                       public void onFailure(Call<TravelDetailBean> call, Throwable t) {
                           dismissLoadingDialog();
                           ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                       }
                   });
       }
   */
    private void getGoldTip() {
        ApiStore.getInstance().getApiService(UrlContainer.Request.BASE_GATE_URL).getReturnGoldTip(((MyApplication) getApplication()).getRequestFieldMap(), orderNum).enqueue(new Callback<ReturnGoldTipBean>() {
            @Override
            public void onResponse(Call<ReturnGoldTipBean> call, Response<ReturnGoldTipBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getMsg_code() == 200 && response.body().getAttachment().getAlertCode() == 1) {
                        layoutReturnGoldTip.setVisibility(View.VISIBLE);
                        returnGoldTip.setText(response.body().getAttachment().getAlertMsg());
                        findViewById(R.id.layout_return_gold_tip).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent();
                                intent.setClass(mContext, WebViewActivity.class);
                                intent.putExtra(IntentKey.INTENT_WEBVIEW_URL, response.body().getAttachment().getAlertHref());
                                startActivity(intent);
                            }
                        });
                    }
                }
            }

            @Override
            public void onFailure(Call<ReturnGoldTipBean> call, Throwable t) {
                //ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            }
        });
    }


    public class GridViewAdapter extends BaseAdapter {
        private int selectPos = -1;
        private List<CheckPositionBean.AttachmentBean.ListBean> reason_list = new ArrayList<>();

        public void replaceAll(List<CheckPositionBean.AttachmentBean.ListBean> list) {
            if (list != null) {
                reason_list.clear();
                reason_list.addAll(list);
            }
            notifyDataSetChanged();
        }

        public String getSelectId() { //没有点选返回"-1"
            if (selectPos == -1) {
                return "-1";
            } else {
                return reason_list.get(selectPos).getId();
            }
        }

        @Override
        public int getCount() {
            return reason_list.size();
        }

        @Override
        public Object getItem(int position) {
            return reason_list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = View.inflate(ReturnCarActivity.this, R.layout.item_flowlayout, null);
            TextView textView = (TextView) view.findViewById(R.id.text_button);
            textView.setText(reason_list.get(position).getReason());
            if (selectPos == position) {
                textView.setBackgroundResource(R.drawable.bg_button_choose);
                textView.setTextColor(Color.parseColor("#2A6CFF"));

            } else {
                textView.setBackgroundResource(R.drawable.bg_button_unchoose);
                textView.setTextColor(Color.parseColor("#999999"));
            }

            view.setOnClickListener(v -> {
                if (position == selectPos) {
                    selectPos = -1;
                } else {
                    selectPos = position;
                }
                notifyDataSetChanged();
                scrollContent.fullScroll(NestedScrollView.FOCUS_DOWN);
            });
            return view;
        }
    }


    @Override
    public void onBackPressed() {
        if (canBack) {
            AppManager.getAppManager().finishActivity();
        }
    }

    private void showBottomSheetDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.bottom_sheet_dialog, null);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        handleList(view, dialog);
        dialog.show();
    }

    private void handleList(View contentView, BottomSheetDialog dialog) {
        Type returnCarOptionsType = new TypeToken<List<AppConstants.DataBean.ReturnCarPositionOptionsBean>>() {
        }.getType();
        String returnCarOptions = SPUtils.getInstance(mContext).getStringValue(SPKey.RETURN_CAR_OPTIONS, "[{\"name\":\"地面\",\"type\":\"pic\"},{\"name\":\"地下一层\",\"type\":\"poi\"},{\"name\":\"地下二层\",\"type\":\"poi\"},{\"name\":\"地下三层\",\"type\":\"poi\"},{\"name\":\"地下四层\",\"type\":\"poi\"},{\"name\":\"地下五层\",\"type\":\"poi\"},{\"name\":\"地下六层\",\"type\":\"poi\"},{\"name\":\"地下七层\",\"type\":\"poi\"}]");
        List<AppConstants.DataBean.ReturnCarPositionOptionsBean> returnCarPositionOptionsBeanList = new Gson().fromJson(returnCarOptions, returnCarOptionsType);
        RecyclerView recyclerView = contentView.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        rcAdapter = new BottomDialogAdapter(returnCarPositionOptionsBeanList);
        recyclerView.setAdapter(rcAdapter);
        rcAdapter.setOnItemClickListener((adapter, view, position) -> {
            SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_SPINNER_NAME, returnCarPositionOptionsBeanList.get(position).getName());//缓存
            choose_type_tv.setText(returnCarPositionOptionsBeanList.get(position).getName());
            return_car_in_park_ground.setText(returnCarPositionOptionsBeanList.get(position).getName());
            if (returnCarPositionOptionsBeanList.get(position).getType().equals("poi")) {
                returnCarIn.setVisibility(View.VISIBLE);
                returnCarPicsGridView.setVisibility(View.GONE);
                onGround = "0";
            } else if (returnCarPositionOptionsBeanList.get(position).getType().equals("pic")) {
                returnCarIn.setVisibility(View.GONE);
                returnCarPicsGridView.setVisibility(View.VISIBLE);
                onGround = "1";
                if (datas == null || datas.size() < 6) {
                    Intent intent = new Intent(mContext, ReturnCarCameraActivity.class);
                    intent.putExtra("orderId", orderId);
                    startActivity(intent);
                }
            }
            SPUtils.getInstance(mContext).putStringValue(SPKey.RETURN_CAR_POSITION, onGround);
            dialog.dismiss();
        });
        rcAdapter.notifyDataSetChanged();
    }

}




